<style media="screen" lang="less">
  #captcha-root{
    // margin-bottom: 10px;
  }
  .sms-code{
    height: 40px;
    color: #555555;
    margin-left: 7px;
    border: 1px solid #dde0e0;
  }
</style>

<template>
  <div id="captcha-root">
    <span class="input-group-btn">
      <button class="btn btn-default sms-code" type="button" @click="sendSmsCode">发送验证码</button>
    </span>

    <modal v-model="modal.visible" :verify="true" @modal-cancel-event="customCancelEvent" @modal-ok-event="customOkEvent" :modal-id="2" :ok-text="modal.okText" :title="modal.title">
      <h4 style="text-align:left;">您的手机号为：{{ cellphone }}</h4>
      <p class="sms-code-content" v-html="modal.content"></p>
    </modal>
  </div>
</template>

<script>
import Modal from './modal.vue'
import SuccessDialog from 'success_alert'
import ErrorDialog from 'error_alert'
import {EventBus} from '../eventBus'

export default {
  components: {
    Modal
  },
  props: {
    type: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      cellphone: "",
      modal: {
        title: "发送手机验证码",
        content: "",
        visible: false,
        okText: "确认发送"
      }
    }
  },
  methods: {
    sendSmsCode() {
      if (!this.isValidCellphone()) {
        ErrorDialog.show('请填写正确手机号码！')
        return false
      } else {
        this.modal.visible = !this.modal.visible
        this.getCaptcha()
      }
    },
    isValidCellphone() {
      let result =  this.cellphone != '' && (this.cellphone != undefined) && (/^1\d{10}$/.test(this.cellphone))
      //let style = "border-color:#d8271c;"
      //if(result) {
      //style = "border-color: #dde0e0;"
      //}
      //EventBus.$emit('getCellphoneInputStyle', style)
      return result
    },
    getCaptcha() {
      let self = this
      $.get("/captcha/get_data", function(data) {
        self.modal.content = data
      })
    },
    isUniq() {
      let result = 'false'
      if(this.type == 'uniq') {
        result = 'true'
      }
      return result
    },
    refreshCapcha() {
      $("#captcha-root .simple_captcha_refresh_button a").click()
    },
    customOkEvent() {
      let cellphone = this.cellphone
      let captcha = $('#captcha').val()
      let captchaKey = $("input:hidden[name='captcha_key']").val()
      let self = this
      if (captcha) {
        let data = {
          mobile: cellphone,
          uniq: self.isUniq(),
          captcha: captcha,
          captcha_key: captchaKey,
          authenticity_token: AUTH_TOKEN
        }
        $.ajax({
          url: '/sms',
          method: 'POST',
          data: data,
          success: function(data) {
            self.modal.visible = !self.modal.visible
            SuccessDialog.show("短信验证码已发送至您手机：" + cellphone + ",请注意查收")
          },
          error: function(resp) {
            self.modal.visible = !self.modal.visible
            let msg;
            if (resp.responseText) {
              msg = $.parseJSON(resp.responseText);
              if (msg.error === 'ttl_limit') {
                ErrorDialog.show("请" + msg.limit + "秒后再发送验证码");
              } else if (msg.error === 'mobile_taken') {
                ErrorDialog.show("手机号" + msg.mobile + "已注册");
              } else if (msg.error === 'invalid_captcha') {
                ErrorDialog.show("您输入的图片验证码不正确");
              } else if (msg.error === 'not_mobile') {
                ErrorDialog.show("不是有效的手机号码");
              } else if (msg.error === 'to_frequently') {
                self.refreshCapcha();
                ErrorDialog.show("一小时内同一手机号发送次数不能超过3次");
              } else {
                ErrorDialog.show();
              }
            } else {
              ErrorDialog.show();
            }

          }
        })
      }
    },
    customCancelEvent() {}
  },
  watch: {
    'modal.content': function() {
      $("#captcha-root").off('click', '.simple_captcha_refresh_button a').on('click', '.simple_captcha_refresh_button a', function() {
        $.ajax({
          url: $(this).attr('href'),
          dataType: 'text',
          global: false,
          data: {
            authenticity_token: AUTH_TOKEN
          },
          success: function(resp) {
            return eval(resp);
          },
          error: function(resp) {
            return false;
          }
        });
        return false
      })
    }
  },
  beforeMount() {
    EventBus.$on('getCellphone', cellphone => {
      this.cellphone = cellphone
    })
  }
}
</script>
